package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

	@Autowired
	private StringRedisTemplate template;

	@Override
	public void setVerifyCode(String phone, String code) {

		String key = RedisKeys.VERIFY_CODE.join(phone);
		// 第三个参数是时间长度,第四个参数是时间单位
		template.opsForValue().set(key, code, RedisKeys.VERIFY_CODE.getTime(), TimeUnit.SECONDS);
	}

	@Override
	public String getVerifyCode(String phone) {
		String key = RedisKeys.VERIFY_CODE.join(phone);
		return template.opsForValue().get(key);
	}

	public void setToken(String token,UserInfo user) {
		String key = RedisKeys.VERIFY_TOKEN.join(token);
		// 把user对象转换成json格式的字符串存储在redis中
		String value = JSON.toJSONString(user);
		template.opsForValue().set(key,value, RedisKeys.VERIFY_TOKEN.getTime(),TimeUnit.SECONDS);
	}

	@Override
	public UserInfo getUserByToken(String token) {
//		AssertUtil.hasLength(token, "");
		if(!StringUtils.hasLength(token)){
			return null;
		}
		String key = RedisKeys.VERIFY_TOKEN.join(token);
		if(template.hasKey(key)){
			// 重置有效时间
			template.expire(key,RedisKeys.VERIFY_TOKEN.getTime(),TimeUnit.SECONDS );
			// 获取到登录的对象并且返回
			String value = template.opsForValue().get(key);
			return JSON.parseObject(value, UserInfo.class);
		}
		return null;
}

}
